from machine import Pin, PWM
import time

class Buzzer:
    def __init__(self, pin_num):
        # 初始化PWM对象，频率设置为1kHz，占空比为0（静音）
        self.pwm = PWM(Pin(pin_num), freq=1000, duty=0)
        self.is_on = False
        
    def on(self, frequency=1000, duty=512):
        """打开蜂鸣器并设置频率和音量"""
        # duty范围通常是0-1023，512表示50%占空比
        self.pwm.freq(frequency)
        self.pwm.duty(duty)
        self.is_on = True
        
    def off(self):
        """关闭蜂鸣器"""
        self.pwm.duty(0)
        self.is_on = False
        
    def beep(self, frequency=1000, duration=0.5, duty=512):
        """发出指定频率和持续时间的蜂鸣声"""
        self.on(frequency, duty)
        time.sleep(duration)
        self.off()
        
    def play_tone(self, frequency, duration):
        """播放指定频率和持续时间的音调"""
        self.beep(frequency, duration)
        
    def play_melody(self, melody, tempo=120):
        """播放简单的旋律
        melody格式：[(频率1, 节拍1), (频率2, 节拍2), ...]
        节拍值：1=全音符, 2=二分音符, 4=四分音符, 8=八分音符等
        """
        # 计算每个节拍的持续时间（秒）
        beat_duration = 60 / tempo
        
        for frequency, beats in melody:
            note_duration = beat_duration / beats
            if frequency > 0:
                self.play_tone(frequency, note_duration * 0.9)  # 0.9是为了在音符之间留一点间隙
            else:
                time.sleep(note_duration)  # 休止符
            
    def deinit(self):
        """释放PWM资源"""
        self.off()
        self.pwm.deinit()